package com.offcn.sellergood.controller;

import com.offcn.entity.PageResult;
import com.offcn.entity.Result;
import com.offcn.entity.StatusCode;
import com.offcn.sellergood.entity.SpecificationEntity;
import com.offcn.sellergood.pojo.Specification;
import com.offcn.sellergood.service.SpecificationService;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/****
 * @Author:ujiuye
 * @Description:
 * @Date 2021/2/1 14:19
 *****/
@Api(tags = "SpecificationController")
@RestController
@RequestMapping("/specification")
@CrossOrigin
public class SpecificationController {

    @Autowired
    private SpecificationService specificationService;

    // 据主键id查询：包含规格和规格选项
    @GetMapping("{id}")
    public Result findById(@PathVariable("id") Long id){
        try {
            SpecificationEntity entity = specificationService.findById(id);
            return new Result(true,StatusCode.OK,"查询规格和规格选项成功",entity);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,StatusCode.ERROR,"查询规格和规格选项失败",null);
        }
    }

    // 增加
    @PostMapping
    public Result insert(@RequestBody SpecificationEntity specificationEntity){
        try {
            specificationService.insert(specificationEntity);
            return new Result(true,StatusCode.OK,"添加规格和规格选项成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,StatusCode.ERROR,"添加规格和规格选项失败");
        }
    }

    // 修改:这里的id是规则的id
    @PutMapping("{id}")
    public Result update(@PathVariable("id") Long id,@RequestBody SpecificationEntity specificationEntity){
        try {
            specificationEntity.getSpecification().setId(id);
            specificationService.update(specificationEntity);
            return new Result(true,StatusCode.OK,"修改规格和规格选项成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,StatusCode.ERROR,"修改规格和规格选项失败");
        }
    }

    // 删除
    @DeleteMapping("{id}")
    public Result delete(@PathVariable("id") Long id){
        try {
            specificationService.delete(id);
            return new Result(true,StatusCode.OK,"删除规格和规格选项成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,StatusCode.ERROR,"删除规格和规格选项失败");
        }
    }

    // 查询规格下拉列表
    @GetMapping("/selectOptions")
    public Result<List<Map>> selectOptions(){
        try {
            List<Map> list = specificationService.selectOptions();
            return new Result(true,StatusCode.OK,"查询规格下拉列表成功",list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,StatusCode.ERROR,"查询规格下拉列表失败",null);
        }
    }
}
